$(document).ready(function(id) {
    
    //    $('#objects').leftScrollbar(); 
    
    var count_dropped_hits = 0;
  
    // Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    };

                
    /*  checks if an object was already registered */
    function exist_object(id){
        for(var i = 0;i<data.images.length;++i){
            if(data.images[i].id == id)
                return i;
        }
        return -1;
    }
				
    /* triggered when stop resizing an object */
    function resizestop(event, ui) {
        //calculate and change values to obj (width and height)
        var $this 		= $(this);
        var objid		= $this.find('.ui-widget-content').attr('id');
        var objwidth            = ui.size.width;
        var objheight           = ui.size.height;
				
        var index 		= exist_object(objid);
				
        if(index!=-1) { //if exists (it should!) update width and height
            data.images[index].width 	= objwidth;
            data.images[index].height 	= objheight;
        }
    }
    makeObjAction();
    $('#background').droppable({
        accept	: '.ui-wrapper', /* accept only draggables from #objects */
        drop	: function(event, ui) {
            var $this 		= $(this);
            dropCallback($this,event,ui);
        }
    });
			
    /* User presses the download button */
    $('#submit').click(function(){
        var data = {
            "images": [
            {
                "id" : "obj_0" ,
                "src" : $('#obj_0').attr('src')	,
                "width" : $('#obj_0').width(), 
                "height" : $('#obj_0').height()
            }
            ],
            "texts":[]
        };
        if($('#background').find('.obj_item').length>0)
        {
            $('#background').find('.obj_item').each(function(){
                if($(this).attr('id')!='obj_0')
                {
                    var elem            = $(this).find(".ui-wrapper");
                    var objsrc          = elem.find('img').attr('src');
                    var objwidth        = parseFloat(elem.width());
                    var objheight       = parseFloat(elem.height());
					
                    /* for top and left we decrease the top and left of the droppable element */
                    var objtop          = elem.position().top+$(this).position().top;
                    var objleft         = elem.position().left+$(this).position().left;
                    var objrotate       = elem.getTransform().rotate*180/Math.PI;
                    var objid           = elem.find('.ui-widget-content').attr('id');
                    var objround_corner = false;
                    if(typeof elem.attr('corner') !='undefined' || elem.attr('corner')!='')
                        objround_corner=elem.attr('corner');
                    var objshadow       = false;
                    if(typeof elem.attr('shadow') !='undefined' || elem.attr('shadow')!='')
                        objshadow=elem.attr('shadow');
               
               
                    var newObject = { 
                        'id' 		: objid,
                        'src' 		: objsrc,
                        'width'             : objwidth,
                        'height'            : objheight,
                        'top' 		: objtop,
                        'left' 		: objleft,
                        'rotation'          : objrotate,
                        'roundcorner'       : objround_corner,
                        'shadow'            : objshadow
                    };
                    data.images.push(newObject);
                }
            });
        }
        if($('#background').find('.text').length>0)
        {
            $('#background').find('.text').each(function(){
                var tobjtext         = $(this).find('.text_dis').html();
                var tobjtop          = $(this).position().top;
                var tobjleft         = $(this).position().left;
                var tobjrotate       = $(this).getTransform().rotate*180/Math.PI;
                var tobjid           = $(this).attr('id');
                var tobjfont         = $(this).css('font-family');
                var tobjsize         = parseFloat($(this).css('font-size'));
                var tobjcolor        = $(this).find('.text_dis').css('color');
                var tobjshadow       = true;                
                if(typeof $(this).attr('shadow') !='undefined' && $(this).attr('shadow')!='')
                {
                    tobjshadow=$(this).attr('shadow');
                }
                var objText={
                    'id' 		:tobjid,
                    'text'              :tobjtext,
                    'font'              :tobjfont,
                    'size'              :tobjsize,
                    'color'             :tobjcolor,
                    'top'               :tobjtop,
                    'left'              :tobjleft,
                    'shadow'            :tobjshadow,
                    'rotation'          :tobjrotate
                };
                data.texts.push(objText);
            });
        }
        var dataString  = JSON.stringify(data);
        $.ajax({
            type: "POST",
            url: "/process.php",
            data: "action=member_edit_image&jsondata="+dataString,
            dataType: 'json',
            success: function(msg){
                if(msg.status=='ok'){
                    
            }
            }
        });
    });
  
    
    jQuery.mlp = {
        x:0,
        y:0
    }; // Mouse Last Position
    $(document).mousemove(function(e){
        jQuery.mlp = {
            x:e.pageX,
            y:e.pageY
        }
    });
    function notNans(value){
        if(isNaN(value)){
            return 0;
        } else {
            return value
        }
    }
    $.fn.ismouseover = function(overThis) {  
        var result;
        this.eq(0).each(function() {  
            var offSet = $(this).offset();
            var w = Number($(this).width())
            + notNans(Number($(this).css("padding-left").replace("px","")))
            + notNans(Number($(this).css("padding-right").replace("px",""))) 
            + notNans(Number($(this).css("border-right-width").replace("px","")))
            + notNans(Number($(this).css("border-left-width").replace("px",""))) ;
            var h = Number($(this).height()) 
            + notNans(Number($(this).css("padding-top").replace("px",""))) 
            + notNans(Number($(this).css("padding-bottom").replace("px","")))
            + notNans(Number($(this).css("border-top-width").replace("px","")))
            + notNans(Number($(this).css("border-bottom-width").replace("px","")));
            if(offSet.left<jQuery.mlp.x && offSet.left + w > jQuery.mlp.x
                && offSet.top<jQuery.mlp.y &&  offSet.top + h > jQuery.mlp.y)
                {
                result = true;
            } else {
                result = false;
            }
        });  
        return result;
    };  
   
   
       
    $('.template_item').click(function(){
        var $src=$(this).find('img').attr('src').replace("thumb/", "");
        var $id=$(this).find('img').attr('id');
        $('.item_layer').removeClass('full');
        $('#obj_0').attr('src',$src);
        $('#background').attr('class','template_'+$id);
        $(".obj_item").not($('#obj_0')).remove();
    })
    upclick(
    {
        element: 'upImage',
        action: '/process.php?action=upload_card_temp', 
        onstart:
        function(filename)
        {
           
        },
        oncomplete:
        function(response_data) 
        {
            if(response_data!="false")
            {
                var jsonObject = jQuery.parseJSON(response_data);
                var boolAct=false;
                $('#background').find('.obj_item').each(function(){
                    var elem=$(this);
                    if(elem.hasClass('active') && elem.attr('id')!='obj_0' )
                    {
                        var id=elem.attr('id');
                        var currX=elem.position().left;
                        var currY=elem.position().top;
                        var currW=elem.width();
                        var currH=elem.height();
                        var currZ=elem.css('z-index');
                        var height=elem.height();
                        var width=height*jsonObject.width/jsonObject.height;
                        if(width<elem.width())
                        {
                            width= elem.width();
                            height= jsonObject.height / jsonObject.width * width;
                        }
                        var dimensions="height:"+height+"px;width:"+width+"px"; 
                        var posx=currX-(width-currW)/2;
                        var posy=currY-(height-currH)/2;                        
                        var html='<div class="obj_item" id="'+id+'" style="position:absolute;top:'+posy.toString()+'px;left:'+posx.toString()+'px;" ><img style="'+dimensions+';" class="ui-widget-content" src="'+jsonObject.filename+'" /></div>';
                        elem.replaceWith(html);
                        $('.layer_list .layer').each(function(){
                            if($(this).attr('rel')==id)
                            {
                                $(this).replaceWith('<div class="layer" rel="obj_'+nextId+'"><img  src="'+jsonObject.filename+'" />'+ jsonObject.filename.replace(/^.*(\\|\/|\:)/, '')+'</div>');     
                            }
                        });
                        makeObjAction();
                        boolAct=true;
                        return false;
                    }                    
                });
                if(!boolAct)
                {
                    $('#background .item_layer').filter(":visible").each(function(){
                        if(!$(this).hasClass('full'))
                        {
                            var elem=$(this);
                            var height=elem.height();
                            var width=height*jsonObject.width/jsonObject.height;
                            if(width<elem.width())
                            {
                                width= elem.width();
                                height= jsonObject.height / jsonObject.width * width;
                            }
                            var dimensions="height:"+height+"px;width:"+width+"px"; 
                            var posx=elem.position().left+(elem.width()-width)/2;
                            var posy=elem.position().top+(elem.height()-height)/2;
                            var nextId=getNextObjId();
                            var html='<div class="obj_item" id="obj_'+nextId+'" style="position:absolute;top:'+posy.toString()+'px;left:'+posx.toString()+'px;" ><img style="'+dimensions+';" class="ui-widget-content" src="'+jsonObject.filename+'" /></div>';
                            if($('#background').find('.obj_item').length>0)
                            {
                                $('#layer_bg').after('<div class="layer" rel="obj_'+nextId+'"><img  src="'+jsonObject.filename+'" />'+ jsonObject.filename.replace(/^.*(\\|\/|\:)/, '')+'</div>');
                                $('#objtext_01').after(html);
                            }
                            else
                            {
                                $('<div class="layer" rel="obj_'+nextId+'"><img  src="'+jsonObject.filename+'" />'+ jsonObject.filename.replace(/^.*(\\|\/|\:)/, '')+'</div>').appendTo($('#tabs-1 .layer_list'));        
                                $('#background').append(html);
                            }
                            $(this).addClass('full');
                            makeObjAction();   
                            boolAct=true;
                            return false;
                        }
                    })
                    if(!boolAct)
                    {
                        var elem=$('#background');
                        var height=elem.height()/2;
                        var width=height*jsonObject.width/jsonObject.height;
                        if(width>elem.width())
                        {
                            width= elem.width()/2;
                            height= jsonObject.height / jsonObject.width * width;
                        }
                        var dimensions="height:"+height+"px;width:"+width+"px"; 
                        var posx=(elem.width()-width)/2;
                        var posy=(elem.height()-height)/2;
                        var nextId=getNextObjId();
                        var html='<div class="obj_item" id="obj_'+nextId+'" style="position:absolute;top:'+posy.toString()+'px;left:'+posx.toString()+'px;" ><img style="'+dimensions+';" class="ui-widget-content" src="'+jsonObject.filename+'" /></div>';
                        if($('#background').find('.obj_item').length>0)
                        {
                            $('#layer_bg').after('<div class="layer" rel="obj_'+nextId+'"><img  src="'+jsonObject.filename+'" />'+ jsonObject.filename.replace(/^.*(\\|\/|\:)/, '')+'</div>');
                            $('#objtext_01').after(html);
                        }
                        else
                        {
                            $('<div class="layer" rel="obj_'+nextId+'"><img  src="'+jsonObject.filename+'" />'+ jsonObject.filename.replace(/^.*(\\|\/|\:)/, '')+'</div>').appendTo($('#tabs-1 .layer_list'));        
                            $('#background').append(html);
                        }
                        makeObjAction();   
                    }
                }
            }
        }
    });
   
    $('#txtText').keyup(function(){
        $('#objtext_01').css({
            'font-size':$("#fontSize").attr('rel')+'px',
            'font-family':$('#sbSelector').attr('rel')
        }).find('.text_dis').html($('#txtText').val().replace(/\n/g,'<br/>')).css({
            'color':$('#color_pick').val()
        });
        $('.ui-wrapper').transformable({
            scalable:false, 
            skewable:false
        });
        
    })
    $("#fontSize").slider({
        value:25,
        min: 15,
        max: 50,
        step: 1,
        slide: function( event, ui ) {
            $(this).attr('rel', ui.value);
            $('#background').find('.text').css({
                'font-size':ui.value+'px',
                'color':$('#color_pick').val(),
                'font-family':$('#sbSelector').html()
            });
        }
    });
    $('#color_pick').bind('colorpicked', function () {
        $('#background').find('.text_dis').css('color',$(this).val());
    });
    $('#sbHolder').fontSelector();
    $( "#tabs" ).tabs();
    $('#template_scroll').carouFredSel({       
        items               : 2,
        scroll: {
            items           : 2,
            duration        : 250 
        },
        auto : false,
        next: '#tpl_next',
        prev: '#tpl_prev'
    });
    $('#pattern_scroll').carouFredSel({       
        items               : 2,
        scroll: {
            items           : 2,
            duration        : 250 
        },
        auto : false,
        next: '#pattern_next',
        prev: '#pattern_prev'
    });
    
});
function checkMouseDown()
{
    $('#background').bind('mousedown',function(){  
        var arrMouseOver=new Array();
        $('#background .obj_item').each(function(){
            if($(this).find('.ui-wrapper').ismouseover() || $(this).find('div').ismouseover()){
                arrMouseOver.push($(this));
            }
            else
            {
                $(this).removeClass("active");
                $(this).find('.ui-resizable-handle').css("display","none"); 
            }
        })
        var overMaxZIndex=0;
        $.each(arrMouseOver, function(index, value) { 
            var cur = parseInt(value.css('z-index'));
            if(cur>overMaxZIndex)
            {
                overMaxZIndex=cur;
                $('.obj_item').removeClass("active");
                value.addClass("active");  
                value.find('.ui-resizable-handle').css("display","block");
            }
        });
        $('.text').each(function(){
            if($(this).ismouseover())
            {
                $('.obj_item').removeClass("active");
                $(this).addClass("text_active");   
            }
            else
            {
                $(this).removeClass("text_active");  
            }
        })
        reSortObject();
        return true;
    });
}
function getMaxZIndex()
{
    var zmax = 0;
    $('.obj_item').each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;                       
    });
    return zmax;
}
function reSortObject(){       
    var zmax=getMaxZIndex();
    $('.layer_list .layer').each(function(){
        var elem=$('#background #'+$(this).attr('rel'));
        if(elem.hasClass('active'))
        {
            elem.css({
                'z-index':500,
                'overflow':'visible'
            });
        }
        else
        {
            elem.css({
                'z-index':zmax,
                'overflow':'visible'
            }); 
        }
        zmax--;
    })
} 
function dropCallback($this,event,ui)
{
   
};
function makeObjAction() {        
    $('.obj_item img').resizable({
        handles: 'ne, se, sw, nw' 
    //stop	: resizestop 
    }).parent('.ui-wrapper') .draggable({
        revert	: 'invalid'
    });
    $('#background .text').draggable({
        revert	: 'invalid'
    });
    $('.ui-wrapper').transformable({
        scalable:false, 
        skewable:false
    });	
    $('.obj_item').removeClass("active");
    $(".ui-resizable-handle").css("display","none");
    if($('.layer_list .layer').length>0)
    {
        $('.layer_list .layer').click(function(){
            $('.obj_item').removeClass("active");
            $(".ui-resizable-handle").css("display","none");
            if( $('#'+$(this).attr('rel')).length>0)
            {
                $('#'+$(this).attr('rel')).addClass("active");
                $('#'+$(this).attr('rel')).find('.ui-resizable-handle').css("display","block");   
            }            
        })
    }
    $(".layer_list").sortable({        
        start: function(event, ui) {
            $('.obj_item').removeClass("active");
            $(".ui-resizable-handle").css("display","none");
        },
        update : function (event, ui) {                                 
            reSortObject();
        }
    }); 
    reSortObject();
    checkMouseDown();
}; 
function getNextObjId()
{
    var maxId=0;
    $('.obj_item').each(function(){
        maxId=$(this).attr('id').split('_')[1]>maxId?$(this).attr('id').split('_')[1]:maxId;
    })
    return parseInt(maxId)+1;
}